<template>
  <div class="flex justify-between align-center">
    <div>
      <a-checkbox
        v-if="
          options.mode == this.eipZeroCodeWorkSheetMode.add &&
          settingJson &&
          settingJson.form &&
          settingJson.form.submitContinueSaveDataTip == 1
        "
        v-model="saveRetain"
      >
        继续创建时，保留本次提交内容
      </a-checkbox>
    </div>
    <a-space>
      <a-button
        v-if="
          options.mode == this.eipZeroCodeWorkSheetMode.add &&
          settingJson &&
          settingJson.form &&
          settingJson.form.saveDraft
        "
        key="submit"
        ><a-icon type="file-done" />存草稿</a-button
      >

      <a-button
        v-if="
          options.mode == this.eipZeroCodeWorkSheetMode.add &&
          settingJson &&
          settingJson.form &&
          settingJson.form.submitContinue
        "
        key="submit"
        @click="save('submitContinue')"
        ><a-icon type="reconciliation" />{{
          settingJson &&
          settingJson.form &&
          settingJson.form.submitContinueButtonName
            ? settingJson.form.submitContinueButtonName
            : "继续创建"
        }}</a-button
      >
      <template
        v-if="
          options.mode == this.eipZeroCodeWorkSheetMode.edit &&
          options.from.button == null
        "
      >
        <a-button
          :type="item.style"
          v-for="(item, index) in button"
          @click="click(item)"
          :key="index"
          ><a-icon :type="item.icon" v-if="item.icon" />{{
            item.name
          }}</a-button
        >
      </template>

      <a-button type="primary" key="submit" @click="save('submit')"
        ><a-icon type="save" />{{
          settingJson && settingJson.form && settingJson.form.submitButtonName
            ? settingJson.form.submitButtonName
            : "保存"
        }}</a-button
      >
    </a-space>
    <worksheet
      v-if="worksheetOption.visible"
      :visible.sync="worksheetOption.visible"
      :options="{
        rowId: worksheetOption.rowId,
        rowIds: worksheetOption.rowIds,
        zeroCodeId: worksheetOption.zeroCodeId,
        mode: worksheetOption.mode,
        from: worksheetOption.from,
      }"
      @ok="buttonOk"
    ></worksheet>
  </div>
</template>

<script>
import { newGuid } from "@/utils/util";
import { findById, businessData } from "@/services/system/zerocode/run/edit";

export default {
  name: "worksheet-button",
  components: {
    worksheet: () => import("../../worksheet"), //异步注入
  },
  data() {
    return {
      saveRetain: false, //继续创建时，保留本次提交内容
      button: [], //所有按钮
      item: null, //当前点击按钮
      //编辑组件
      worksheetOption: {
        zeroCodeId: null,
        rowId: null,
        visible: false,
        rowIds: [],
        mode: null,
        from: {
          zeroCodeId: null, //工作表
          key: null, //来源控件(用于区分双向关联才解析默认绑定)
          rowId: null, //来源数据RowId,从列表上来时为多个，逗号分割
          button: null, //来源按钮Id,有值则表示从按钮点击来
        },
      },

      settingJson: JSON.parse(this.systemZeroCode.settingJson),
      columnJson: JSON.parse(this.systemZeroCode.columnJson),
    };
  },

  props: {
    systemZeroCode: Object, //当前工作表配置信息
    systemZeroCodeValue: Object, //当前工作表值
    //配置
    options: {
      type: Object,
      default: () => ({
        //低代码Id
        zeroCodeId: {
          type: String,
        },
        //业务Id
        rowId: {
          type: String,
        },
        //所有业务Id,上一页下一页使用
        rowIds: {
          type: Array,
        },
        //模式add新增，edit更新
        mode: {
          type: String,
        },
        //来源参数（只有从关联记录控件点击新增才出现）
        from: {
          zeroCodeId: null, //工作表
          key: null, //来源控件(用于区分双向关联才解析默认绑定)
          rowId: null, //来源数据RowId,从列表上来时为多个，逗号分割
          button: null, //来源按钮Id,有值则表示从按钮点击来
        },
      }),
    },
  },
  created() {
    this.button = this.settingJson.button;
  },
  methods: {
    save(type) {
      let that = this;
      //判断是否从按钮来
      if (that.options.from.button && that.options.from.button.submit.confirm) {
        that.$confirm({
          centered: true,
          title: that.options.from.button.submit.title,
          content: that.options.from.button.submit.content,
          okText: that.options.from.button.submit.ok,
          cancelText: that.options.from.button.submit.cancel,
          onOk() {
            that.$emit("save", {
              type: type,
              saveRetain: that.saveRetain,
            });
          },
          onCancel() {},
          class: "test",
        });
      } else {
        that.$emit("save", {
          type: type,
          saveRetain: this.saveRetain,
        });
      }
    },

    async click(button) {
      let that = this;
      //判断按钮类型
      this.item = button;
      //当前记录，填写字段
      if (
        button.form.target == this.eipZeroCodeFormSettingButtonFormTarget.now &&
        button.form.write == this.eipZeroCodeFormSettingButtonFormWrite.field
      ) {
        that.worksheetOption.mode = that.eipZeroCodeWorkSheetMode.button;
        that.worksheetOption.zeroCodeId = that.options.zeroCodeId;
        that.worksheetOption.from = {
          zeroCodeId: that.options.zeroCodeId, //工作表
          key: null, //来源控件(用于区分双向关联才解析默认绑定)
          rowId: that.options.rowId, //来源数据RowId,从列表上来时为多个
          button: button, //来源按钮Id,有值则表示从按钮点击来
        };
        that.worksheetOption.visible = true;
      }
      //当前记录，填写关联
      else if (
        button.form.target == this.eipZeroCodeFormSettingButtonFormTarget.now &&
        button.form.write ==
          this.eipZeroCodeFormSettingButtonFormWrite.correlation
      ) {
        that.worksheetOption.mode = that.eipZeroCodeWorkSheetMode.button;
        //查找关联记录zeroCodeId
        let correlation = that.$utils.find(
          that.columnJson,
          (f) => f.key == button.form.writeCorrelationKey
        );
        if (correlation != null) {
          that.worksheetOption.zeroCodeId = correlation.options.zeroCodeId;
          that.worksheetOption.rowId = newGuid();
          that.worksheetOption.from = {
            zeroCodeId: that.options.zeroCodeId, //工作表
            key: correlation.key, //来源控件(用于区分双向关联才解析默认绑定)
            rowId: that.options.rowId, //来源数据RowId,从列表上来时为多个
            button: button, //来源按钮,有值则表示从按钮点击来
          };
          that.worksheetOption.visible = true;
        }
      } else if (
        button.form.target ==
          this.eipZeroCodeFormSettingButtonFormTarget.correlation &&
        button.form.write == this.eipZeroCodeFormSettingButtonFormWrite.field
      ) {
        var correlation = that.$utils.find(
          that.columnJson,
          (f) => f.key == button.form.targetCorrelationKey
        );
        if (correlation) {
          that.worksheetOption.mode = that.eipZeroCodeWorkSheetMode.button;
          that.worksheetOption.zeroCodeId = correlation.options.zeroCodeId;
          //对应值
          var value = that.systemZeroCodeValue[correlation.key];
          that.worksheetOption.from = {
            zeroCodeId: that.options.zeroCodeId, //工作表
            key: null, //来源控件(用于区分双向关联才解析默认绑定)
            rowId: value, //来源数据RowId,从列表上来时为多个
            button: button, //来源按钮Id,有值则表示从按钮点击来
          };
          that.worksheetOption.visible = true;
        }
      } else if (
        button.form.target ==
          this.eipZeroCodeFormSettingButtonFormTarget.correlation &&
        button.form.write ==
          this.eipZeroCodeFormSettingButtonFormWrite.correlation
      ) {
        var correlation = that.$utils.find(
          that.columnJson,
          (f) => f.key == button.form.targetCorrelationKey
        );
        if (correlation) {
          that.worksheetOption.mode = that.eipZeroCodeWorkSheetMode.button;

          var systemZeroCodeData = await findById(
            correlation.options.zeroCodeId
          );
          if (systemZeroCodeData.code === that.eipResultCode.success) {
            var correlationWrite = that.$utils.find(
              JSON.parse(systemZeroCodeData.data.columnJson),
              (f) => f.key == button.form.writeCorrelationKey
            );

            that.worksheetOption.zeroCodeId =
              correlationWrite.options.zeroCodeId;
            //对应值
            var value = that.systemZeroCodeValue[correlation.key];
            that.worksheetOption.from = {
              zeroCodeId: that.options.zeroCodeId, //工作表
              key: button.form.targetCorrelationKey, //来源控件(用于区分双向关联才解析默认绑定)
              rowId: value, //来源数据RowId,从列表上来时为多个
              button: button, //来源按钮Id,有值则表示从按钮点击来
            };
            that.worksheetOption.visible = true;
          } else {
            that.$message.error("获取配置错误");
          }
        }
      }
    },

    /**
     * 加载数据
     */
    buttonOk(data) {
      let that = this;
      this.worksheetOption.visible = false;
      if (
        this.item.form.target ==
          this.eipZeroCodeFormSettingButtonFormTarget.now &&
        this.item.form.write == this.eipZeroCodeFormSettingButtonFormWrite.field
      ) {
        //回写自动刷新页面
        this.$emit("reloadData", this.options.rowId);
      }
      //当前记录，填写关联
      else if (
        this.item.form.target ==
          this.eipZeroCodeFormSettingButtonFormTarget.now &&
        this.item.form.write ==
          this.eipZeroCodeFormSettingButtonFormWrite.correlation
      ) {
        //判断关联表类型
        //查找关联记录zeroCodeId
        let find = that.$utils.find(
          that.columnJson,
          (f) => f.key == this.item.form.writeCorrelationKey
        );
        let values = [];
        if (find != null) {
          if (
            [
              this.eipZeroCodeControlCorrelationShowType.select,
              this.eipZeroCodeControlCorrelationShowType.card,
            ].includes(find.options.showType)
          ) {
            if (
              find.options.type == this.eipZeroCodeControlCorrelationType.single
            ) {
              values.push({
                key: that.item.form.writeCorrelationKey,
                value: JSON.stringify([data.data.RowId]),
              });
            } else {
              var v =
                this.systemZeroCodeValue[that.item.form.writeCorrelationKey];
              v.push(data.data.RowId);
              values.push({
                key: that.item.form.writeCorrelationKey,
                value: JSON.stringify(v),
              });
            }
          } else {
            var writeCorrelationKeyValue =
              this.systemZeroCodeValue[that.item.form.writeCorrelationKey];
            var rowIds = writeCorrelationKeyValue.map((m) => m.RowId);
            rowIds.push(data.data.RowId);
            values.push({
              key: that.item.form.writeCorrelationKey,
              value: JSON.stringify(rowIds),
            });
          }
        }

        //更新值
        businessData({
          zeroCodeId: that.options.zeroCodeId,
          rowId: that.options.rowId,
          values: JSON.stringify(values),
        }).then(async function (result) {
          if (result.code == that.eipResultCode.success) {
            that.$message.success(result.msg);
            that.$emit("reloadData", that.options.rowId);
          } else {
            that.$message.error(result.msg);
          }
        });
      }

      //关联表修改关联字段
      else if (
        this.item.form.target ==
          this.eipZeroCodeFormSettingButtonFormTarget.correlation &&
        this.item.form.write == this.eipZeroCodeFormSettingButtonFormWrite.field
      ) {
        //回写自动刷新页面
        this.$emit("reloadData", this.options.rowId);
      }
    },
  },
};
</script>

<style lang="less"></style>
